package com.atguigul.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.vo.MemberRespVo;
import com.atguigul.gulimall.auth.feign.MemberFeignService;
import com.atguigul.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigul.gulimall.auth.vo.UserLoginVo;
import com.atguigul.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGINUSER);
        if (attribute==null){
            //没有登录过
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }


    }






    @PostMapping("/login")
    //由于前端提交的是KV，所以 UserLoginVo 前面不要加@RequestBody.
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
        R login = memberFeignService.login(vo);
        //登录成功后回到商城首页
        if (login.getCode()==0){
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGINUSER,data);
            return "redirect:http://gulimall.com";
        }else {
            //携带错误信息，反馈给页面
            Map<String,String>errors=new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }








    @ResponseBody
    @PostMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
//TODO 1.接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }


        //2。验证码再次验证。key phone value.防止同一个手机号在60秒同又提交验证码。
        //生成4位纯数字code,测试模板仅可以4-6位数字。
        String subcode="";
        for (int i = 0; i <= 200; i++)
        {
            int intFlag = (int)(Math.random() * 10000);

             subcode = String.valueOf(intFlag);
            if (subcode.length() != 4 || subcode.charAt(0) != '9')
            {
                intFlag = intFlag + 1000;
            }
            subcode= String.valueOf(intFlag);
        }
//        String subcode = UUID.randomUUID().toString().substring(0, 5);
        String code =  subcode + "_" + System.currentTimeMillis() ;
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 10, TimeUnit.MINUTES);

        thirdPartyFeignService.sendCode(phone, subcode);
        return R.ok();

    }

    /**
     * @param vo
     * @param result
     * @param redirectAttributes 模拟重定向携带数据
     * @return
     */
    //TODO:重定向携带数据，利用SESSION原理。将数据保存在session中，重定向后将数据取出来；只要跳到下一个页面，取出数据后，session就会将数据删除。
    //Request method 'POST' not supported
    //用户注册->?regist[post]-->转发 /reg.html(路径映射默认都是GET方式访问的)
    @PostMapping("/register")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

//            model.addAttribute("errors",errors);
            //校验出错，转发到注册页
            //为了不反复提高数据，不用转发方式；用重定向方式
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
//            return "reg";
//            return "forward:/reg.html";
        }
        //真正注册，调用远程服务
        String code = vo.getCode();
        String subcode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotEmpty(code)) {
            if (code.equals(subcode.split("_")[0])) {
                //删除验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码正确，调用远程服务
                R r = memberFeignService.regist(vo);

                if (r.getCode()==0){
                    //成功,//注册成功回到首页，登录页
                    return "redirect:/login.html";
                }else{
                    Map<String,String> errors=new HashMap<>();
                    errors.put("msg",r.getData(new TypeReference<String>(){}));
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {//验证码错误，转发到注册页
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute(errors);
                return "redirect:http://auth.gulimall.com/reg.html";

            }

        } else {//验证码为空，转发到注册页
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码为空，错误");
            redirectAttributes.addFlashAttribute(errors);
            return "redirect:http://auth.gulimall.com/reg.html";

        }




    }


}
